package com.bbg.amyam.web.util.menu;

import java.util.ArrayList;
import java.util.List;

public class MenuDescriptor implements java.io.Serializable {

	private List<MenuItem> menus=new ArrayList<MenuItem>();
	private int activeIndex=0;
	private String currentUnitName="";
	
	public MenuDescriptor( List<MenuItem> menulist,
			String[] grantedRoles, String schoolShortName, String viewName) {
		currentUnitName=schoolShortName;
		for(MenuItem item:menulist){
			MenuItem menuItem=verifyMenuItem(item,grantedRoles,schoolShortName,viewName);
			if(menuItem!=null){
				if(menuItem.getId().equals(viewName)){
					menuItem.setActive(true);
				}
				this.menus.add(menuItem);
			}
		}
		
		for(int index=0;index<menus.size();index++){
			if(menus.get(index).isActive()){
				this.activeIndex=index;
				break;
			}
		}
		
		if(activeIndex==0 && this.menus.size()>0){
			this.menus.get(0).setActive(true);
		}
		
	}
	private MenuItem verifyMenuItem(MenuItem menuItem,
			String[] grantedRoles,String schoolShortName,String viewName) {
		if(!menuItem.isAuthorized(grantedRoles)){
			return null;
		}
		if(!menuItem.checkForView(schoolShortName)){
			return null;
		}
		
		MenuItem newMenuItem=new MenuItem(menuItem);
		for(MenuItem child:menuItem.getChildren()){
			MenuItem c=verifyMenuItem(child,grantedRoles,schoolShortName,viewName);
			if(c!=null){
				c.setParent(newMenuItem);
				newMenuItem.addChild(c);
			}
		}
		
		newMenuItem.setUnitName(schoolShortName);
		return newMenuItem;
	}

	public List<MenuItem> getMenus() {
		return menus;
	}

	
	
	public int getActiveIndex() {
		return activeIndex;
	}
	public String getCurrentUnitName() {
		return currentUnitName;
	}
	
}
